package com.tools.handler;

import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
@RequiredArgsConstructor
public class StepHandlerManager {


    private final ApplicationContext applicationContext;

    private final Map<String, StepHandler> stepHandlerMap = new HashMap<>();

    @PostConstruct
    public void init() {
        // 自动注册所有StepHandler实现
        Map<String, StepHandler> handlers = applicationContext.getBeansOfType(StepHandler.class);
        handlers.values().forEach(handler -> {
            String stepCode = handler.getStepCode();
            if (stepHandlerMap.containsKey(stepCode)) {
                log.warn("步骤处理器重复注册: {}", stepCode);
            }
            stepHandlerMap.put(stepCode, handler);
            log.info("注册步骤处理器: {} -> {}", stepCode, handler.getClass().getSimpleName());
        });

        log.info("步骤处理器注册完成，共注册 {} 个处理器", stepHandlerMap.size());
    }

    public StepHandler getHandler(String stepCode) {
        StepHandler handler = stepHandlerMap.get(stepCode);
        if (handler == null) {
            log.warn("未找到步骤处理器: {}", stepCode);
        }
        return handler;
    }

    public void registerHandler(String stepCode, StepHandler handler) {
        stepHandlerMap.put(stepCode, handler);
        log.info("手动注册步骤处理器: {} -> {}", stepCode, handler.getClass().getSimpleName());
    }

    public void unregisterHandler(String stepCode) {
        stepHandlerMap.remove(stepCode);
        log.info("注销步骤处理器: {}", stepCode);
    }

    public boolean containsHandler(String stepCode) {
        return stepHandlerMap.containsKey(stepCode);
    }

    public Map<String, StepHandler> getAllHandlers() {
        return new HashMap<>(stepHandlerMap);
    }

}
